package com.gjy.mybatis.plugin;

import com.google.common.base.Stopwatch;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-10-24 11:08:46
 */
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {
                MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class
        })
})
public class ExecutorTimeInterceptor implements Interceptor {
    private static final Logger log = LoggerFactory.getLogger(ExecutorTimeInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement) args[0];
        BoundSql sql = statement.getBoundSql(args[1]);

        Stopwatch stopwatch = Stopwatch.createStarted();
        try {
            return invocation.proceed();
        } finally {
            stopwatch.stop();
            log.info("sql:{}", sql.getSql());
            log.info("cost:{}", stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

}
